'use client'
import { Button, Card, Form, Image, Message, Select, Slider, Space, Upload } from '@arco-design/web-react'
import React, { useEffect, useRef, useState } from 'react'
import { RequestOptions } from '@arco-design/web-react/es/Upload'
import PromptInput from '@components/PromptInput'
import { models } from '@constants/models'
import Images from '@components/Images'
import { useLocalStorageState } from 'ahooks'
import { omit } from 'lodash-es'
import { useTRPCClient } from '@server/trpc/client'
import { useStorageForm } from '../../../hooks/useStorageForm'
const FormItem = Form.Item
const Option = Select.Option

type FormData = {
  model: string,
  image: string,
  similarity: number,
  promptText: string,
}

const FORM_DATA_STORAGE_KEY = 'img2img_history_form'
const HISTORY_IMAGE_STORAGE_KEY = 'img2img_history_images'

const Page = () => {
  const { form, saveForm } = useStorageForm({
    storageKey: FORM_DATA_STORAGE_KEY,
    ignoreFields: ['image'],
    initValue: {
      model: models[0]?.model,
      image: '',
      similarity: 75,
      promptText: '',
    }
  });
  const [historyImages, setHistoryImages] = useLocalStorageState<string[]>(HISTORY_IMAGE_STORAGE_KEY, { defaultValue: [] })
  const [loading, setLoading] = useState(false)
  const imageName = useRef<string>('');
  const { image } = useTRPCClient();

  const handleUpload = async ({file, onSuccess, onError}: RequestOptions) => {
    // setUploading(true)
    const formData = new FormData()
    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
      Message.error('图片大小不能超过5mb')
      return onError();
    }
    formData.append('image', file)

    try {
      const { name } = await image.uploadImage.mutate(formData)

      imageName.current = name;
      onSuccess()
      return { abort: () => {}, imageName: name }
    } catch (e) {
      onError(e as Error);
    }
  }

  const handleSubmit = async (params: FormData) => {
    saveForm();
    setLoading(true)
    const queueCount = await image.getQueueCount.query();
    if (queueCount) {
      Message.info(`排队中，预计剩余时间${queueCount * 15}秒`)
    }
    try {
      const res = await image.img2img.mutate({
        model: params.model,
        image: imageName.current,
        similarity: params.similarity,
        promptText: params.promptText,
      })
      if (res) {
        const newImages = res.concat(historyImages)
        setHistoryImages(newImages)
      }
    } catch (e) {
      Message.error('生成失败，请重试');
    } finally {
      setLoading(false)

    }
  }

  return (
    <Card title="图生图" className={"max-w-200"}>
      <Form layout="vertical" form={form} onSubmit={handleSubmit}>
        <FormItem rules={[{ required: true }]} required label='模型' field="model">
          <Select
            placeholder='请选择模型'
          >
            {models.map((option) => (
              <Option key={option.model} value={option.model}>
                {option.name}
              </Option>
            ))}
          </Select>
        </FormItem>

        <FormItem rules={[{ required: true }]} required label='上传图片' field="image">
          <Upload
            drag
            accept="image/*"
            imagePreview
            multiple={false}
            limit={1}
            listType="picture-card"
            // beforeUpload={handleUpload}
            customRequest={handleUpload}

          />
        </FormItem>
        <FormItem label='提示词(可不填)' field="promptText">
          <PromptInput />
        </FormItem>
        <FormItem rules={[{ required: true }]} required label='重绘程度' field="similarity">
          <Slider showInput/>
        </FormItem>

        <FormItem>
          <Button shape="round" long loading={loading} size="large" type='primary' htmlType='submit'>生成</Button>
        </FormItem>
      </Form>
      <Images data={historyImages} />
    </Card>
  )
}

export default Page
